import {_} from "./UtilTs";

const fs=require('fs');
const path = require('path');
const sep =  path.sep;

//文件结构  --仅仅为了ide 提示
export class FileProps{
    root: string;
    dir: string;
    package:string;
    base: string;
    ext:string;
    name: string;
    fullPath: string;
}

export class UtilFile{
    static sep = sep;
    static sepLinux = '/';

    //遍历目录
    static listFile(dir:string,fileCb:(file:FileProps)=>void) {
        var root =path.normalize(dir);
        function ls(ff) {

            if(!_.isEmpty(ff)){
                var files = fs.readdirSync(ff);
                for (var fn in files) {
                    var fname = ff + path.sep + files[fn];
                    var stat = fs.lstatSync(fname);
                    if (stat.isDirectory() == true) {
                        ls(fname);
                    }
                    else {
                        var finalPath = path.normalize(fname);
                        var file =<FileProps> path.parse(finalPath);
                        file.package =UtilFile.pathToPackage(finalPath.replace(root,''));
                        file.fullPath = file.dir +UtilFile.sep+ file.base;
                        fileCb(file);
                    }
                }
            }
        }
        ls(dir);
    }

    //获取上级本目录完整路径
    static getCurrentPath(dirname):string{
        var filePath =  path.join(dirname, '/');
        return path.normalize(filePath);
    }

    //目录字符串转换成包的形式
    static pathToPackage(path:string){
        return path.replace(UtilFile.sep,'.');
    }

    //写字符串到文件
    static writeString(str,path){
        fs.writeFile(path, str, function (err) {
            if (err) throw err;
            console.log('It\'s saved!'); //文件被保存
        });
    }

}